package org.example.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.Exception.RollBackException;
import org.example.SpringSecurityTestApplication;
import org.example.dao.GoodsDao;
import org.example.domain.*;
import org.example.domain.response.ResponseResult;
import org.example.services.GoodsService;
import org.example.utils.FileUtil;
import org.example.utils.PageConvertPageBeanUtil;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.UUID;


@Slf4j
@Transactional
@Service
public class GoodsServiceImpl  implements GoodsService {
        @Resource
        private GoodsDao goodsDao;
    @Override
    public ResponseResult saveGoods(Goods goods) {
        try {
            goodsDao.insert(goods);
            goodsDao.infoInsert(goods.getGoodsId(),goods.getInformation());
            log.info("新增订单，成功{}",goods);
            return ResponseResult.success("新增订单成功",goods);
        }catch (Exception e){
            e.printStackTrace();
            log.info("新增订单失败");
            throw new RollBackException("新增订单失败");
        }
    }

    @Override
    public ResponseResult updateGoods(Goods goods) {
        Goods goodsRes=goodsDao.selectById(goods.getGoodsId());
        if(goodsRes==null){
            log.warn("商品修改：商品基本信息查询失败");
            throw new RollBackException("无该商品信息，请刷新");
        }
        try{
            goodsDao.updateById(goods);
            if(goods.getInformation()!=null){
                goodsDao.deleteInfoByGoodsId(goods.getGoodsId());
                goodsDao.infoInsert(goods.getGoodsId(),goods.getInformation());
            }
            log.info(goodsRes.getGoodsId()+"修改商品成功");
            return ResponseResult.success("修改商品成功");
        }catch (Exception e){
            e.printStackTrace();
            log.warn("商品修改失败");
            throw new RollBackException("商品修改失败");
        }
    }

    @Override
    public ResponseResult deleteGoods(Integer goodsId) {
        try {
            Goods good=goodsDao.selectById(goodsId);
            if(good==null){
                log.warn("商品删除:商品基本信息查询失败");
                throw new RollBackException("无该商品，请刷新");
            }
            goodsDao.deleteById(goodsId);
            goodsDao.deleteInfoByGoodsId(goodsId);
            log.warn("商品删除成功");
            return ResponseResult.success("删除商品成功");
        }catch (RollBackException e){
            e.printStackTrace();
            log.warn("删除书籍失败");
            throw new RollBackException("删除商品失败");
        }
    }

    @Override
    public ResponseResult getAllGoods() {
        List<Goods> goods = goodsDao.selectList(null);
        for(Goods goods1:goods){
            String s = goodsDao.selectInfoByGoodsId(goods1.getGoodsId());
            goods1.setInformation(s);
        }
        return ResponseResult.success("查询所有成功",goods);
    }

    @Override
    public ResponseResult getGoodsByGoodsId(int goodsId) {
        try {
            Goods goods = goodsDao.selectById(goodsId);
            String s = goodsDao.selectInfoByGoodsId(goods.getGoodsId());
            goods.setInformation(s);
            return ResponseResult.success("通过商品id查询成功",goods);
        }catch (NullPointerException e){
            log.warn(goodsId+"：通过id查询失败，case：无该商品id数据");
            throw new RollBackException("无该商品数据");
        }catch (Exception e){
            log.warn(goodsId+"：通过id查询失败，case："+e.getCause().getMessage());
            throw new RollBackException("查询商品失败");
        }
    }

    @Override
    public ResponseResult uploadGoodsImg(MultipartFile file, int goodsId) {
        Goods goods = goodsDao.selectById(goodsId);
        if(goods == null){
            return ResponseResult.failed("商品不存在，请刷新后重试");
        }
        ApplicationHome applicationHome = new ApplicationHome(SpringSecurityTestApplication.class);
        //将文件保存在当前项目同目录中的images中
        //打包前是当前java文件目录下，打包后是在项目目录下
        String path = applicationHome.getDir().getAbsolutePath()
                + File.separator  + "images"
                + File.separator  + "goodsCover";

        if(file.isEmpty()){
            return ResponseResult.failed("文件为空");
        }

        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String fileNameNew = UUID.randomUUID().toString().replace("-", "") + suffixName;
        //保存图片
        if (!FileUtil.uploadImage(file,path,fileNameNew)) {
            log.warn("商品图片上传失败");
            return ResponseResult.failed("商品图片上传失败");
        }
        //删除原来的图片
        String img1 = goods.getImg();
        String fileNameOld = img1.substring(img1.lastIndexOf(File.separator) + 1);
        log.info("删除文件{}成功",fileNameOld);
        int flag = FileUtil.deleteFile(path, fileNameOld);
        if( flag == 0){
            log.warn("商品原图片删除失败");
            FileUtil.deleteFile(path,fileNameNew);
            return ResponseResult.failed("图片更新失败，原图删除失败");
        }

        String img = File.separator  + "images"
                + File.separator  + "goodsCover"
                + File.separator + fileNameNew;
        try {
            Goods goods1 = new Goods();
            goods1.setGoodsId(goodsId);
            goods1.setImg(img);
            goodsDao.updateById(goods1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RollBackException("上传商品图片失败");
        }
        goods.setImg(img);
        return ResponseResult.success("商品图片上传成功",goods);
    }

    //    分页
    public ResponseResult getGoodsByPage(int currentPage, int pageSize){
        Page<Goods> page = new Page(currentPage, pageSize);
//        封装
        Page<Goods> goodsPage = goodsDao.selectPage(page, null);
        PageBean<Goods> pageBean = PageConvertPageBeanUtil.convert(goodsPage);
        log.info("分页查询讨论：成功{}",pageBean);
        return ResponseResult.success("分页查询商品成功",pageBean);
    }

//  通过名字查询
    public ResponseResult getGoodsByName(String name,int pageSize,int currentPage){
        try {
            Page<Goods> page = new Page<>(currentPage,pageSize);
            QueryWrapper<Goods> wrapper = new QueryWrapper<>();
            wrapper.like("goods_name",name);
            Page<Goods> goodsPage = goodsDao.selectPage(page, wrapper);
            PageBean<Goods> pageBean=PageConvertPageBeanUtil.convert(goodsPage);
            log.info("按商品名称分页查询成功");
            return ResponseResult.success("分页查询名字成功",pageBean);
//            return getGoodsByPage(page,wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("按商品名称分页查询失败");
            return null;
        }
    }

//    通过type查询
public ResponseResult getGoodsByType(String type,int pageSize,int currentPage){
    try {
        Page<Goods> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.like("type",type);
        Page<Goods> goodsPage = goodsDao.selectPage(page, wrapper);
        PageBean<Goods> pageBean=PageConvertPageBeanUtil.convert(goodsPage);
        log.info("按商品名称分页查询成功");
        return ResponseResult.success("分页查询名字成功",pageBean);
    } catch (Exception e) {
        e.printStackTrace();
        log.warn("按商品名称分页查询失败");
        return null;
    }
}

}
